package com.carful.xigua.modules.common.advice;

import com.carful.xigua.modules.common.entity.Rest;
import com.carful.xigua.modules.common.entity.RestBody;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * sql 异常统一处理
 *
 * @author ad
 * Date 2024/4/11 13:31
 * Description
 */

@RestControllerAdvice
@Order(2)
@Slf4j
public class DataBaseExceptionHandler {

    @ExceptionHandler(SQLException.class)
    public Rest<?> unify(SQLException e) throws SQLException {
        log.error("", e);
        String regex;
        Matcher matcher;

        regex = "Duplicate entry '(.*?)' for key '(.*?)'";
        matcher = Pattern.compile(regex).matcher(e.getMessage());
        if (matcher.find()) {
            // 获取被占用的值
            String value = matcher.group(1);
            // 获取数据库冲突键
            String keys = matcher.group(2);
            return RestBody.build(503, null, keys + " " + value + " 已经存在", null);
        }
        regex = "Field '(.*?)' doesn't have a default value";
        matcher = Pattern.compile(regex).matcher(e.getMessage());
        // 如果存在信息
        if (matcher.find()) {
            // 获取被占用的值
            String value = matcher.group(1);

            return RestBody.build(503, null, value + "不能为空", null);
        }
        return RestBody.build(503, null, e.getMessage(), null);
    }

    /**
     *  完整性约束被破坏处理
     * @return: java.lang.String
     */
    public String integrityConstraint(SQLIntegrityConstraintViolationException e) {
        // 匹配数据库报错信息
        String regex = "Duplicate entry '(.*?)' for key '(.*?)'";
        Matcher matcher = Pattern.compile(regex).matcher(e.getMessage());
        // 如果存在信息
        if (matcher.find()) {
            // 获取被占用的值
            String value = matcher.group(1);
            // 获取数据库冲突键
            String keys = matcher.group(2);

            return keys + " " + value + " 已经存在";
        }
        return "数据已存在";
    }

}
